﻿using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Gamey.SNES
{
    // This code owes its existence to the following website:
    // http://romhack.wikia.com/wiki/SNES_header
    public class SmcHeaderReader : RomReader
    {
        class NameFieldReader : FieldReader
        {
            static readonly int[] PossibleHeaderOffsets = new int[] { 0x7fc0, 0xffc0, 0x81c0, 0x101c0 };
            static readonly Regex NameMatcher = new Regex(@"^[A-Z1-9 \-\!]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            public NameFieldReader() : base(-1, 21)
            { }

            public override bool TryReadField(byte[] bytes, out string value)
            {
                value = null;

                foreach (int possibleOffset in PossibleHeaderOffsets)
                {
                    string possibleName = Encoding.ASCII.GetString(bytes, possibleOffset, Length);
                    if (NameMatcher.IsMatch(possibleName))
                    {
                        value = possibleName.Trim().ToUpper();
                        return true;
                    }
                }

                return false;
            }
        }

        static readonly IDictionary<string, FieldReader> FieldReaders = new Dictionary<string, FieldReader>
        {
            { "Name", new NameFieldReader() }
        };

        protected override string RomFileExtension
        {
            get { return ".smc"; }
        }

        protected override IDictionary<string, FieldReader> GetFieldReaders()
        {
            return FieldReaders;
        }
    }
}
